package org.csu.xzypetstore.controller;


import org.csu.xzypetstore.domain.Product;
import org.csu.xzypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.List;

@Controller
@SessionAttributes({"productList"})
@RequestMapping("/product")
public class searchProduct {

    @Autowired
    private CatalogService catalogService;

    @PostMapping("/search")
    public String searchProduct(String keyword, Model model) {
        if (keyword == null || keyword.length() < 1) {
            return "catalog/searchProduct";
        } else {
            List<Product> productList = catalogService.searchProductList(keyword.toLowerCase());
//            processProductDescription(productList);
            model.addAttribute("productList", productList);
            return "catalog/searchProduct";
        }
    }

    private void processProductDescription(Product product) {
        String[] temp = product.getDescription().split("\"");
        product.setDescriptionImage(temp[1]);
        product.setDescriptionText(temp[2].substring(1));
    }

    private void processProductDescription(List<Product> productList) {
        for (Product product : productList) {
            processProductDescription(product);
        }
    }
}
